package com.gy.paidao.main;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.AutocompletePrediction;
import com.google.android.gms.location.places.AutocompletePredictionBuffer;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.PlaceBuffer;
import com.google.android.gms.location.places.PlaceDetectionApi;
import com.google.android.gms.location.places.PlaceFilter;
import com.google.android.gms.location.places.PlaceLikelihood;
import com.google.android.gms.location.places.PlaceLikelihoodBuffer;
import com.google.android.gms.location.places.PlaceReport;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.location.places.internal.AutocompletePredictionEntity;
import com.gy.paidao.BaseActivity;
import com.gy.paidao.MyApplication;
import com.example.mapdemo.R;
import com.gy.paidao.main.adapter.SearchAdapter;
import com.gy.paidao.main.bean.MyLocationBean;
import com.gy.paidao.util.AnimUtil;
import com.gy.paidao.util.LogUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @author GY
 * @date 16/4/21
 * @Description:
 */
public class MapSearchActivity extends BaseActivity implements
        AdapterView.OnItemClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    private ImageView imgBcak;
    private TextView tvCancel;
    private EditText etLoc;
    private ListView listView;
    private SearchAdapter mAdapter;
    private List<MyLocationBean> datas,normalData;
    public final static int POI_DISTANCE = 10000;// 附近点距离
    private GoogleApiClient mGoogleApiClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map_search);
        setViews();
    }

    @Override
    protected void initVariable() {
        datas = new ArrayList<>();
        normalData = new ArrayList<>();
        mAdapter = new SearchAdapter(this,datas);
        mGoogleApiClient = new GoogleApiClient
                .Builder(this)
                .addApi(Places.GEO_DATA_API)
                .addApi(Places.PLACE_DETECTION_API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
        mGoogleApiClient.connect();

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }

        PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
                .getCurrentPlace(mGoogleApiClient, null);
        result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
            @Override
            public void onResult(PlaceLikelihoodBuffer likelyPlaces) {
                if(likelyPlaces.getCount() > 0){
                    datas.clear();
                    normalData.clear();
                }
                for (PlaceLikelihood placeLikelihood : likelyPlaces) {
                    MyLocationBean bean = new MyLocationBean();
                    String name = placeLikelihood.getPlace().getName().toString();
                    if(!TextUtils.isEmpty(name) && !"Unnamed Road".equals(name)){
                        bean.name = name;
                        bean.latitude = placeLikelihood.getPlace().getLatLng().latitude+"";
                        bean.longitude = placeLikelihood.getPlace().getLatLng().longitude+"";
                        normalData.add(bean);
                    }
//                    LogUtil.e(String.format("Place '%s' has likelihood: %g",
//                            placeLikelihood.getPlace().getName(),
//                            placeLikelihood.getLikelihood()));
                }

                datas.addAll(normalData);
                mAdapter.notifyDataSetChanged();
                likelyPlaces.release();
            }
        });



    }

    @Override
    protected void setTitleViews() {

    }

    @Override
    protected void setViews() {
        imgBcak = (ImageView) findViewById(R.id.map_search_img_back);
        tvCancel = (TextView) findViewById(R.id.map_search_tv_cancel);
        etLoc = (EditText) findViewById(R.id.map_search_et_loc);
        listView = (ListView) findViewById(R.id.map_search_listview);

        imgBcak.setOnClickListener(this);
        tvCancel.setOnClickListener(this);
        listView.setAdapter(mAdapter);
        listView.setOnItemClickListener(this);
        etLoc.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String search = s.toString();
                if(!TextUtils.isEmpty(search)){
                    doSearch(search);
                } else {
                    datas.clear();
                    datas.addAll(normalData);
                    mAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void doClickAction(int viewId) {
        super.doClickAction(viewId);
        switch (viewId){
            case R.id.map_search_img_back:
                this.finish();
                AnimUtil.pushRightInAndOut(this);
                break;
            case R.id.map_search_tv_cancel:
                etLoc.setText("");
                break;
        }
    }

    private void doSearch(String search){
        PendingResult pendingResult =
                Places.GeoDataApi.getAutocompletePredictions(mGoogleApiClient, search, null, null);
        pendingResult.setResultCallback(new ResultCallback<AutocompletePredictionBuffer>() {
            @Override
            public void onResult(@NonNull AutocompletePredictionBuffer autocompletePredictions) {
                if(autocompletePredictions.getCount() > 0)
                    datas.clear();
                for(AutocompletePrediction prediction : autocompletePredictions){
                    final MyLocationBean bean = new MyLocationBean();
                    String name = prediction.getDescription();
                    if(!TextUtils.isEmpty(name) && !"Unnamed Road".equals(name)){
                        bean.name = name;

                    }
                    mAdapter.notifyDataSetChanged();
                    LogUtil.e(prediction.getDescription()+"--");
                    Places.GeoDataApi.getPlaceById(mGoogleApiClient,prediction.getPlaceId()).setResultCallback(new ResultCallback<PlaceBuffer>() {
                        @Override
                        public void onResult(@NonNull PlaceBuffer places) {
                            if(places.getCount() > 0){
                                Place place = places.get(0);
                                bean.latitude = place.getLatLng().latitude+"";
                                bean.longitude = place.getLatLng().longitude+"";
                                datas.add(bean);
                                mAdapter.notifyDataSetChanged();
                            }
                        }
                    });

                }
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        MyLocationBean result = datas.get(position);
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putSerializable("loc",result);
        intent.putExtras(bundle);
        setResult(105,intent);
        this.finish();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        LogUtil.e("onConnected----");
    }

    @Override
    public void onConnectionSuspended(int i) {
        LogUtil.e("onConnectionSuspended------");
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }
}
